using System;
using System.Globalization;
using System.Runtime.Serialization;

namespace Bookvar.ObjectModel.Actions.Collaboration
{
    [Serializable]
    [DataContract]
    public class AddTopicAction : ActionBase
    {
        private Guid parentTopicId;
        private Topic newTopic;
        private int index;

        [DataMember]
        public Topic NewTopic
        {
            get { return newTopic; }
            set { newTopic = value; }
        }

        [DataMember]
        public Guid ParentTopicId
        {
            get { return parentTopicId; }
            set { parentTopicId = value; }
        }

        [DataMember]
        public int Index
        {
            get { return index; }
            set { index = value; }
        }

        public AddTopicAction( Guid parentTopicId, Topic newTopic, int index )
        {
            this.parentTopicId = parentTopicId;
            this.newTopic = newTopic;
            this.index = index;
        }

        public override void Execute( IExecutionContext context )
        {
            if ( context == null )
            {
                throw new ArgumentNullException( "context" );
            }
            if ( ParentTopicId == Guid.Empty )
            {
                throw new InvalidOperationException( "TopicId is not properly set" );
            }

            try
            {
                context.ExecutionMode = ExecutionMode.Execution;
                Topic parent = context.MainTopic.FindTopic( ParentTopicId );
                parent.SubTopics.Insert( index, NewTopic );
                context.HighlightTopic( NewTopic, PublisherGuid );
            }
            finally
            {
                context.ExecutionMode = ExecutionMode.None;
            }
        }

        public override string ToString()
        {
            return string.Format( CultureInfo.CurrentCulture, "ParentTopicId: {0}, NewTopicId: {1}, NewTopicName: {2}",
                                  ParentTopicId, NewTopic.ID,
                                  NewTopic.Name );
        }
    }
}